﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows;

namespace DalamudManager.Models
{
    public static class NetPluginList
    {
        const string PluginListData = "https://gitee.com/BAKAOLC/dalamud-service/raw/master/PluginList.json";
        const string DownloadPath = "https://gitee.com/BAKAOLC/dalamud-service/raw/master/Plugins";

        public static PluginInfo[] List { get; private set; }

        public static async void Update(Action callback = null)
        {
            await Task.Run(() =>
            {
                try
                {
                    var jsonStr = Utils.HttpGET(PluginListData);
                    var data = JArray.Parse(jsonStr);
                    List<PluginInfo> records = new();
                    foreach (var plugin in data)
                    {
                        var info = GetPluginInfo(plugin);
                        if (info != null)
                            records.Add(info);
                    }
                    List = records.ToArray();
                }
                catch (Exception e)
                {
                    MessageBox.Show("更新网络插件列表时发生错误：\n" + e.Message);
                }
                callback?.Invoke();
            });
        }

        public static PluginInfo GetPluginInfo(JToken plugin)
        {
            try
            {
                var result = PluginInfo.Parse(plugin.ToString());
                result.Path = Path.Combine(DownloadPath, (string)plugin["InternalName"], "plugin.zip").Replace(@"\", "/");
                return result;
            }
            catch (Exception e)
            {
                MessageBox.Show($"解析数据时发生错误：\n" + e.Message + "\n原数据：" + plugin.ToString());
            }
            return null;
        }
    }
}
